layui.define(['layer', 'table','admin','config'], function (exports) {
    var $ = layui.jquery;
    var layer = layui.layer;
    var table = layui.table;
    var admin = layui.admin;
    var config = layui.config;

    var treetable = {
        mData : {},
        // 渲染树形表格
        render: function (param) {
            // 检查参数
            if (!treetable.checkParam(param)) {
                return;
            }
            var token = config.getToken();
            if(token){
                param.headers = {
                    Authorization : "Bearer "+token
                }
            }else{
                location.replace('./login.html');
            }
            treetable.resetParam(param);
            table.render(param);
        },
        resetParam:function (param){
            var parseData = param.parseData;
            param.height = "full-200";
            param.method = param.method || "post";
            param.treeSpid= param.treeSpid || -1;
            param.treeIdName= param.treeIdName || 'id';
            param.treePidName= param.treePidName ||'parentId',
            param.page = false;
            param.limit = -1
            param.response={
                statusCode:1
            }
            param.parseData = (function(parseData){
                return function(res){
                    if(res && res.code ==-1){
                        location.replace('./login.html');
                    }
                    if(res.code != 1 || res.code !="1"){
                        return res;
                    }
                    var tNodes;
                    if(parseData){
                        tNodes =  parseData(res.data)
                    }
                    var mmData = [];
                    treetable.mData[param['elem']] = mmData;
                    // 补上id和pid字段
                    for (var i = 0; i < tNodes.length; i++) {
                        var tt = tNodes[i];
                        if (!tt.id) {
                            if (!param.treeIdName) {
                                layer.msg('参数treeIdName不能为空', {icon: 5});
                                return;
                            }
                            tt.id = tt[param.treeIdName];
                        }
                        if (!tt.pid) {
                            if (!param.treePidName) {
                                layer.msg('参数treePidName不能为空', {icon: 5});
                                return;
                            }
                            tt.pid = tt[param.treePidName];
                        }
                    }
                    treetable.sort(param.treeSpid, tNodes,mmData);
                    res.data = mmData;
                    return res;
                }
            })(parseData);
            param.cols[0][param.treeColIndex].templet = function (d) {
                    var mmData = treetable.mData[param['elem']];
                    var mId = d.id;
                    var mPid = d.pid;
                    var isDir = d.isParent;
                    var emptyNum = treetable.getEmptyNum(mPid, mmData);
                    var iconHtml = '';
                    for (var i = 0; i < emptyNum; i++) {
                        iconHtml += '<span class="treeTable-empty"></span>';
                    }
                    if (isDir) {
                        iconHtml += '<i class="layui-icon layui-icon-triangle-d"></i> <i class="layui-icon layui-icon-layer"></i>';
                    } else {
                        iconHtml += '<i class="layui-icon layui-icon-file"></i>';
                    }
                    iconHtml += '&nbsp;&nbsp;';
                    var ttype = isDir ? 'dir' : 'file';
                    var vg = '<span class="treeTable-icon open" lay-tid="' + mId + '" lay-tpid="' + mPid + '" lay-ttype="' + ttype + '">';
                    return vg + iconHtml + d[param.cols[0][param.treeColIndex].field] + '</span>'
                }
            var doneCallback = param.done;
            param.done = (function(doneCallback){
                return function (res, curr, count) {
                    $(param.elem).next().addClass('treeTable');
                    // $('.treeTable .layui-table-page').css('display', 'none');
                    $(param.elem).next().attr('treeLinkage', param.treeLinkage);
                    if (param.treeDefaultClose) {
                        treetable.foldAll(param.elem);
                    }
                    if (doneCallback) {
                        doneCallback(res, curr, count);
                    }
                }
            })(doneCallback);
        },
        // 对数据进行排序
        sort: function (s_pid, data,mData) {
            for (var i = 0; i < data.length; i++) {
                if (data[i].pid == s_pid) {
                    var len = mData.length;
                    if (len > 0 && mData[len - 1].id == s_pid) {
                        mData[len - 1].isParent = true;
                    }
                    mData.push(data[i]);
                    treetable.sort(data[i].id, data,mData);
                }
            }
        },
        // 计算缩进的数量
        getEmptyNum: function (pid, data) {
            var num = 0;
            if (!pid) {
                return num;
            }
            var tPid;
            for (var i = 0; i < data.length; i++) {
                if (pid == data[i].id) {
                    num += 1;
                    tPid = data[i].pid;
                    break;
                }
            }
            return num + treetable.getEmptyNum(tPid, data);
        },
        // 展开/折叠行
        toggleRows: function ($dom, linkage) {
            var type = $dom.attr('lay-ttype');
            if ('file' == type) {
                return;
            }
            var mId = $dom.attr('lay-tid');
            var isOpen = $dom.hasClass('open');
            if (isOpen) {
                $dom.removeClass('open');
            } else {
                $dom.addClass('open');
            }
            $dom.closest('tbody').find('tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var pid = $ti.attr('lay-tpid');
                var ttype = $ti.attr('lay-ttype');
                var tOpen = $ti.hasClass('open');
                if (mId == pid) {
                    if (isOpen) {
                        $(this).hide();
                        if ('dir' == ttype && tOpen == isOpen) {
                            $ti.trigger('click');
                        }
                    } else {
                        $(this).show();
                        if (linkage && 'dir' == ttype && tOpen == isOpen) {
                            $ti.trigger('click');
                        }
                    }
                }
            });
        },
        // 检查参数
        checkParam: function (param) {
            if (!param.treeColIndex && param.treeColIndex != 0) {
                layer.msg('参数treeColIndex不能为空', {icon: 5});
                return false;
            }
            return true;
        },
        // 展开所有
        expandAll: function (dom) {
            $(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var ttype = $ti.attr('lay-ttype');
                var tOpen = $ti.hasClass('open');
                if ('dir' == ttype && !tOpen) {
                    $ti.trigger('click');
                }
            });
        },
        // 折叠所有
        foldAll: function (dom) {
            $(dom).next('.treeTable').find('.layui-table-body tbody tr').each(function () {
                var $ti = $(this).find('.treeTable-icon');
                var ttype = $ti.attr('lay-ttype');
                var tOpen = $ti.hasClass('open');
                if ('dir' == ttype && tOpen) {
                    $ti.trigger('click');
                }
            });
        }
    };

    layui.link(layui.cache.base + 'treetable-lay/treetable.css');

    // 给图标列绑定事件
    $('body').on('click', '.treeTable .treeTable-icon', function () {
        var treeLinkage = $(this).parents('.treeTable').attr('treeLinkage');
        if ('true' == treeLinkage) {
            treetable.toggleRows($(this), true);
        } else {
            treetable.toggleRows($(this), false);
        }
    });

    exports('treetable', treetable);
});
